‹header›
Click to edit Master text styles
Second level
Third level
Fourth level
Fifth level
‹date/time›
‹footer›
‹#›
You have the freedom to comment your code as much as you like -- some programmers write code with no comments at all; others write several lines of comments for each line of C++ code. It's all up to you. Keep in mind, though, that if anyone else will ever read your code, you'll probably want to add comments. Even if you are the only one who will ever read your code, you should add comments. It sounds implausible, but programmers often don't understand code they've written weeks ago!
Where is the file iostream.h?
This file is located somewhere in your include path. The include path indicates the directories on your computer in which to search for a file, if the file is not located in the current directory. Why do I need to include iostream.h?
In this case, iostream.h is a file containing code for input/output operations. You need to include iostream.h so that the compiler knows about the word cout, which appears a couple of lines below.
Every C++ program must have what is known as a main function. When you run the program, the program will go through every line of code in the main function and execute it. If your main is empty, then your program will do nothing. For now, the important thing to remember is that the function body is the part enclosed in { ... } ("curly braces"). The { indicates the beginning of the function, and the } indicates the end of the function. The function body is the stuff in between.
For now, don't worry about how cout works, just know how to use it.
In Pascal a program is a single unit, called program, which contains variables, functions, and procedures nested within. In C++, no such nesting occurs, and the main function is the equivalent of the program. The type of the value returned by a function is written before the function name, and there is no special function keyword. The parentheses () signify a function declaration to the compiler. They are present even if the function has no arguments (as in main()). C++ does not distinguish between functions and procedures. A procedure is simply a function returning void. The braces {} are the equivalent of begin and end. In C++ all statements are terminated with a semicolon, even the last statement of a block, but there is no semicolon following the closing brace. The operation cout << is like the Pascal write; there is no special writeln analog. To obtain a blank line, simply send a string containing a newline ‘\n’. Many Pascal compilers have an analog to the #include directive that opens another file and includes its contents for compilation. Sometimes this is implemented as a pseudocomment directive (*$I filename*).
Here is a program which will print out the message.
Hello, C++.
Note: Every C program contains a function called main. This is the start point of the program.
printf(“Hello, C++.\n”);
Prints the worlds on the screen. The text to be printed is enclosed in double quotes. The \n at the end of the text tells the program to print a newline as part of the output.
Most C programs are in lower case letters. You will usually find upper case letters used in preprocessor definitions or inside quotes as parts of character strings. C is case sensitive, that is, it recognises a lower case letter and it’s upper case equivalent as being different.
Character constants are rarely used, since string constants are more convenient. A string constant is surrounded by double quotes eg "Brian and Dennis". The string is actually stored as an array of characters. The null character '\0' is automatically placed at the end of such a string. This acts as a string terminator.
A character is not the same type as a single character string. This is important.
The rules for numeric constants (integer, real) are essentially the same, though C is a bit more flexible.
1.In C/C++ non-printing characters may be embedded in either character or string constants by using various escapes – e.g.
 \0 – null character
\n – new line
\t – tab
\b – backspace
\f – formfeed
\\ - \
\’ – ‘
\” – “
\ddd – Character whose OCTAL code is ddd – e.g. ‘\101’ is the same as ‘A’
2. String constants are terminated by a null character \0. Thus, the total space allocated for a string is one more than the number of characters in it.
3. String constants may be continued over more than one line by having a \ be the very last character on the line to be continued – e.g.
“This is a string constant that ex\
Tends over more than one line.”
C++ and some ANSI C compilers only
4. A string constant may be continued over more than one line by simply closing the quotes on one line and re-opening them on the next – e.g.
“This is a string constant that ex”
“tends over more than one line.”
In C (but not C++), an integer constant declared this way may NOT be used to specify the size of an array in most cases.
Of course, your memory changes over time. Your friend moves across country and has a new phone number, and your friend's new phone number will replace the old one in your memory. Over time, as you acquire new friends, your memory will keep changing to store different pieces of information. Likewise, a computer's memory can change over time, if you tell it to. Since variables are your access point to your computer's memory, it makes sense that you'd be able to change the information in a computer's memory; otherwise, they wouldn't be called variables (they'd be called statics). Why should you care about variables? Variables are the essence of any computer program! Without variables, computers would be useless. Imagine a program which asks the user for two numbers and adds them together, and prints the result. # AddTwoNumbers Enter the first number: 2 Enter the second number: 5 The sum of 2 and 5 is 7. # Sounds simple, right? But let's do a little role-playing to see what the computer has to do to execute this program. Instead of this interaction between a person and a computer, let's imagine the same kind of conversation between two people, Sol and Frank. Sol: Hey Frank, I just learned how to add two numbers together.
Frank: Cool!
Sol: Give me the first number.
Frank: 2.
Sol: Ok, and give me the second number.
Frank: 5.
Sol: Ok, here's the answer: 2 + 5 = 7.
Frank: Sheesh! This guy is unbelievable!
After Frank says "2", Sol has to store that number in his memory somewhere. It may be stored in short-term memory, but he has to store it somewhere before Frank gives him the second number. Even if Frank were to give him two numbers in the same sentence, Sol would have to store the numbers somewhere in his memory to add them together. In the sample program described above, the computer would most likely store "2" in a variable, then store "5" in a variable, and then calculate the sum by calculating the sum of the numbers store in the two variables.
Although there are similarities between a person's memory and a computer's memory, there are some pretty big differences. In C++, you need to grab a little piece of the computer's memory before you can use it.
What can you name your variables? In general, variable names can be composed of letters, numbers, and underscores (_). However, C++ reserves certain keywords which have special meaning to the language, and you are not allowed to use any of these keywords as variables names. Some examples of C++ keywords are int, for, else, and class. You can, however, use keywords in the middle of a variable name, such as "foreign" or "classical". For a complete list of C++ keywords, please see references on C/C++. Programming languages vary regarding how strict they require you to be when declaring a variable's type. Some languages, like Perl, do not require you to announce the type of a variable. Other languages require you to declare some variables as numbers and others as text-strings, for example. C++, a strongly-typed language, requires you to be even more specific than that. Instead of declaring a variable as a number, you must say whether it will store integers or decimals. In C++, the type of an integer is int and the type of a decimal is float (floating-point number).
In some languages, variables are initialized to 0 - that is, a variable's initial value will be 0. This is not true of C++! Sometimes your variables will be initialized to 0, but sometimes they will be initialized with garbage. As you might anticipate, this can cause some nasty bugs. Let's take a look at another sample program. #include <iostream.h> int main() { int myAge; cout << "My age is " << myAge << endl; return 0; } You might expect the program to output "My age is 0". In fact, the output of this program is unreliable. On one system you may get output of "My age is 11"; another system may output "My age is 0"; yet another system may output "My age is 3145". That's what it means to have a variable initialized with garbage. It is always a good idea to initialize your variables with some value. If you don't know what a variable's initial value should be, initialize it to 0. Initializing a variable is easy. Let's fix the above program so that it always outputs "My age is 22". The first line of the main function initializes myAge by assigning it a value immediately. #include <iostream.h> int main() { int myAge = 22; cout << "My age is " << myAge << endl; return 0; }
In C, a variable must be declared before it can be used. Variables can be declared at the start of an block of code, but most are found at the start of each function. Most local variables appear when the function is called, and are destroyed on return from that function.
A declaration begins with the type, followed by the name of one or more variables.
Declarations can also be spread out. This allows space for an explanatory comment to be added. Variables can also be initialised when they are declared, this is done by adding an equals sign and the required value after the declaration.
int high = 250;
Variable high is declared as integer and is initialised to 250.
All of the integer types plus the char are called the integral types. float and double are called the real types.
Every variable has a name and a value. The name is used to identify the variable, the value is used to store data. There is a limitation on what these names can be. Every variable name in C must start with a letter, the rest of the name can consist of letters, numbers and underscore characters. C recognises upper and lower case characters as being different. Finally, you cannot use any of C's keywords like main, while, switch etc as variable names.
It is conventional to avoid the use of capital letters in variable names. These are used for names of constants. Some old implementations of C only use the first 8 characters of a variable name. Most modern ones don't apply this limit though.
The rules governing variable names also apply to the names of functions. We shall meet functions later on in the course.
For reasons not explained here, variables can only store finite numbers. Suppose that the size of a particular data type, that we'll call a gorb, is 1 byte. That means that gorbs can only represent 28*1 = 28 = 256 distinct values. So, gorbs might be able to store only the numbers between 0 and 255 (inclusive). Any number that you tried to store in a gorb which was smaller than 0, or larger than 255, would not be stored correctly; it would be stored as one of the values between 0 and 255. However, maybe you want to be able to store positive and negative numbers in gorbs, in which case you'd only be able to store 128 negative numbers and 128 positive numbers. Since we need to be able to store 0 also, you might decide that the range of values for a gorb is -128 to 127.
We've already learned about two different data types. What are the sizes of these data types, and what are the limits on the kinds of values that they can store? We just saw that a data type whose size is 1 byte can store 256 distinct values. Data types of size 2 bytes can store 28*2 = 216 = 65536 different values. Using the same formula, we determine that data types of size 4 bytes can store 28*4 = 232 = 4,294,967,296.
Unfortunately, the size of data types like int and float are not standard across all systems. The size of an int depends on your operating system and your hardware. Here are some typical values for ints and floats, along with some other important data types.
type -- typical size -- description
short -- 2 bytes -- stores a short (i.e., small) integer
int -- 4 bytes -- stores an integer
long -- 4 bytes -- stores a long (i.e., large) integer
float -- 4 bytes -- stores a floating-point number
double -- 8 bytes -- stores a "double-precision" floating-point number
In C (but not C++), an integer constant declared this way may NOT be used to specify the size of an array in most cases.
New ANSI Standard C++
bool b;
1.C does not use a word like var to introduce variable declarations – it just declares them.
2.C does not have a separate type for boolean values. Int is used, with 0=false and 1=true. The new ANSI C++ standard calls for a built in type bool with values false and true, but not all C++ compilers implement it yet.
3.In addition to the scalar types shown above, C has
short int (may be abbreviated short)
long int (may be abbreviated long)
double (double-precision real)
4. Any integer type (including char) may be prefixed by unsigned – e.g.
unsigned int i;
1. In C, the difference between these examples is that the first creates a new type named simply “student”, while the second two create a new type whose name is “struct student”. The third example combines the type and variable declarations into one declaration.
2. In C++, all three examples create a new type that can be called EITHER student or struct student.
1. In C, the difference between these examples is that the first creates a new type named simply “student”, while the second two create a new type whose name is “struct student”. The third example combines the type and variable declarations into one declaration.
2. In C++, all three examples create a new type that can be called EITHER student or struct student.
1. In C, the difference between these examples is that the first creates a new type named simply “student”, while the second two create a new type whose name is “struct student”. The third example combines the type and variable declarations into one declaration.
2. In C++, all three examples create a new type that can be called EITHER student or struct student.
One reason for the power of C is its wide range of useful operators. An operator is a function which is applied to values to give a result. You should be familiar with operators such as +, -, /.
Arithmetic operators are the most common. Other operators are used for comparison of values, combination of logical states, and manipulation of individual binary digits. The binary operators are rather low level for the brief of this course, so are not covered here.
Operators and values are combined to form expressions. The values produced by these expressions can be stored in variables, or used as a part of even larger expressions.
The assignment will save the value of the expression in variable y.
Probably the most common assignment operator is the equals sign (=). It is called "assignment" because you are "assigning" a variable to a value. This operator takes the expression on its right-hand-side and places it into the variable on its left-hand-side. So, when you write x = 5, the operator takes the expression on the right, 5, and stores it in the variable on the left, x.
This code shows why you might want to throw away the return value of an operator. Look at the third line, x = 5. We're using the assignment operator here to place the value 5 in the variable x. Since the expression x = 5 returns a value, and we're not using it, then you could say we are ignoring the return value. However, note that a few of lines down, we are very interested in the return value of an operator. The addition operator in the expression x + y returns the sum of its left-hand-side and right-hand-side. That's how we are able to assign a value to sum. You can think of it as sum = (x + y), since that's what it's really doing.
An example above shows how it can be taken advantage of this return value.
All this code does is store the value in each of the four variables left, top, right, and bottom. How does it work? It starts on the far right-hand side. It sees bottom = 4. So it places the value 4 in the variable bottom, and returns the value it stored in bottom (which is 4). Since bottom = 4 evaluates to 4, the variable right will also get the value 4, which means top will also get 4, which means left will also get 4. Phew! Of course, this code could have just as easily been written //these four variables represent the sides of a rectangle int left; int top; int right; int bottom; //make it a square whose sides are 4 left = 4; top = 4; right = 4; bottom = 4; and it would have done the exact same thing. The first way is more compact, and you're more likely to see it written the first way. But both ways are equally correct, so use whichever you prefer.
*, / and % will be performed before + or - in any expression. Brackets can be used to force a different order of evaluation to this. Where division is performed between two integers, the result will be an integer, with remainder discarded. Modulo reduction is only meaningful between integers. If a program is ever required to divide a number by zero, this will cause an error, usually causing the program to crash.
The mod (%) is simply the remainder produced by dividing two integers. In the example shown in the table above, if we treat 10 / 6 as an integer divison, the quotient is 1 (rather than 1.666) and the remainder is 4. Hence, the variable remainder will get the value 4.
These are powerful operators which can cause confusion if you try to do too many things on one command line. You are recommended to restrict your use of ++ and - to ensure that your programs stay readable.
Versions where the operator occurs before the variable name change the value of the variable before evaluating the expression.
You can mix the types of values in your arithmetic expressions. char types will be treated as int. Otherwise where types of different size are involved, the result will usually be of the larger size, so a float and a double would produce a double result. Where integer and real types meet, the result will be a double.
The function sqrt finds the square root of a double.
The cast is made by putting the bracketed name of the required type just before the value. (double) in this example.
When to Cast
Casting a variable is a complicated name for a simple concept. When you cast a variable from one type to another, all you are doing is telling the computer to use a different type to store the variable. Why would you need (or want) to do this? Let's say you declared a variable of type short. In most cases, that would mean that the largest positive value you could store would be 32,767. But somewhere in your program, you realize that you're going to have to do a calculation which could increase the value over this maximum. Perhaps you are computing very large Pythagorean triplets. To calculate the value of c (the hypotenuse), you need to take the square root of the quantity a2 + b2. But what if a or b is very large? Then squaring that number will make it much, much larger -- and if the value becomes bigger than 32,767 your values will not be what you expected (if you had used a short to store a or b. Remember, a short can only store the values between -32,768 and +32,767, so if you try to store a number out of this range, your data will be incorrect!
So, the solution is to cast. We can cast the numbers to a larger data type, such as an int or a long, for the purposes of the calculation -- and then we can cast them back to a short when we are done, since the final value for c will probably be small enough to be stored in a short.
This is a somewhat trivial example, since in this case you could store the numbers in ints or longs from the beginning and not worry about it! A more useful example might be if you have a number which represents an average. You'll probably want to represent the number with a floating-point type like a float or a double so that it is accurate while you are computing it (otherwise you'd only be able to store a value like "26" instead of "26.3141885"). Let's say that you want to display the value in a table, yet the table would look cluttered if you displayed "26.3141885", so you decide to simply display the integer portion, 26. You can cast the float to an int and then display the int in the table -- since ints can't store floating-point numbers, the decimal portion of "26.3141885" will be truncated and you will be left with "26".
How to Cast
Casting in C++ is easy. Let's say that you have a float storing a number like "26.3141885", and you want to have an int storing the integer portion instead. Here's how to do it:
int GetAverage() { // assume that regularAverage and specialAverage store two floats float totalAverage = regularAverage + specialAverage; // cast totalAverage to an int int truncatedAverage = (int) totalAverage; // return the truncated value return truncatedAverage; } There's a little bit of syntax that you haven't seen before, but the key part to notice is the line of code that reads int truncatedAverage = (int) totalAverage. What we're doing here is taking a float, totalAverage, which stores some kind of decimal number (like 82.41832), and getting rid of the ".41832" part by casting it to an int. That works because the int is only capable of storing integers, so it simply stores the integer portion of totalAverage.
C has no special type to represent logical or boolean values. It improvises by using any of the integral types char, int, short, long, unsigned, with a value of 0 representing false and any other value representing true. It is rare for logical values to be stored in variables. They are usually generated as required by comparing two numeric values. This is where the comparison operators are used, to compare two numeric values and produce a logical result.
Note that == is used in comparisons and = is used in assignments. Comparison operators are used in expressions like the ones below.
In the last example, all arithmetic is done before any comparison is made.
These comparisons are usually used to control an if statement or a for or a while loop. These will be introduced in a later chapter.
You are undoubtedly familiar with equality operators, even if you don't know it. An equality operator is one that tests a condition such as "is less than", "is greater than", and "is equal to". You will find it useful to be able to compare two numbers using expressions like "x is less than y".
Now that we have pseudo-code, writing the C++ code is as simple as "translating" your pseudo-code into C++.
You'll notice some new syntax in this example, but don't worry about it too much. Pay close attention to the very first line, which checks to make sure that the amount requested is less than the account balance. The way it works is, if the expression between parentheses (()) evaluates to true, then the first block of code will be read. That is, the code inside the first set of curly braces ({}) will be executed. If the expression in parentheses evaluates to false, on the other hand, then the second block of code (the code following the word else) will be read. In this case, the first block of code withdraws the amount requested by the customer, while the second block of code withdraws nothing, and notifies the customer.
Before talking about operators, we'll take a quick aside into booleans, since we'll need to know what a boolean is before discussing operators. A boolean value is one that can be either true or false. No other values are allowed. Booleans and boolean operations are at the heart of programming. Many times in a program, you'll want to do one thing if a certain condition is true, and a different thing if the condition is false. For example, when processing a series of checkboxes, you may want to take an action only if a box is checked, and do nothing otherwise. That's when you'll want to use a boolean. Most programming languages have a type for booleans, usually called "boolean" or "bool". Some C++ compilers recognize the type bool, others do not. For now, assume that your compiler supports the bool type. We'll discuss what to do if your compiler doesn't, in a moment. In order to use boolean logic to your advantage, you need to learn about the three basic boolean operations. They are called and, or, and not. Each operation takes either one or two boolean inputs, and returns a boolean output. They are often represented by symbols known as "gates", shown above.
In C/C++ these logical connectives employ a technique known as lazy evaluation. They evaluate their left hand operand, and then only evaluate the right hand one if this is required. Clearly false && anything is always false, true || anything is always true. In such cases the second test is not evaluated. Not operates on a single logical value, its effect is to reverse its state. It can be used as follows.
What does this code do?
It initializes two variables, franIsTired and franMustWakeUpEarly, to true and false, respectively. Then, in the third line of code (not including comments!), we determine that Fran will go to sleep if and only if the "and" operation is true -- that is, if both inputs to the "and" operation are true. In this case, the first input is true and the second input is false. Since "and" requires both inputs to be true in order for the output to be true, but one of the inputs is false, the output will be false. So, the variable bedTime will store the value false. Also, take note that the variable names used here are lengthy. How you decide to program is up to you, but often times it's better to have lengthier variable names that are readable, rather than short, obfuscated variable names like "i" or "zz". (The names in this example may have gone overboard, though.)
What does this code do?
This example is very similar to the example involving Fran (see previous slide with AND operator), except notice the key difference: whether or not Graham goes to sleep is determined differently. Graham will go to sleep if he is tired or if he needs to wake up early. Whereas Fran would go to sleep only if both conditions were true, Graham will go to sleep if either condition (or both) is true. Therefore, the value of bedTime is true.
What does this code do?
This example illustrates the "not" operator. At the end of this block of code, the variable julianIsPeppy will take on the opposite value of julianStayedUpLate. If julianStayedUpLate were false, then julianIsPeppy would be true. In this case, the opposite is true, so julianIsPeppy gets a value of false.
C also provides a set of bit manipulation operators. These are quite specialised, so interested students would do well to check a textbook for details.
Local variables are declared within a function, and can only be used within that function. This is usually no problem, since when another function is called, all required data is passed to it as arguments. Alternatively, a veriable can be declared so it is available to all functions. This is called a global variable. Modern programming practice recommends against the excessive use of global variables. They can lead to poor program structure, and tend to clog up the available name space for variables.
A global variable is declared as normal, but outside any of the program's functions. This is usually done at the beginning of the program file, but after preprocessor directives. The variable is not declared again in the body of the function which accesses it.
An exception to the non-declaration of global variables occurs where a program has several source files. Where a global variable is declared in one file, but used by functions from another, then the variable is called an external variable in these functions, and must be declared as such. That declaration must be proceeded by the word extern. The external variable is really a special type of global variable. The declaration is required so the compiler can find the type of the variable without having to search through several source files for the declaration.
Global and external variables can take any type available to local variables. They can be initialised in the same way, but the initialisation takes place when the program starts up, before execution of the main function.
Another class of local variable is the static type. A static can only be acessed from the function in which it was declared, rather like a local variable. The static variable is not destroyed on exit from the function, instead its value is preserved, and becomes available again when the function is next called. Static variables are declared as local variables, but the declaration is preceeded by the word static.
Static variables can be initialised as normal, however this takes place once only when the program starts up, not every time their function is called.
When declaring a reference variable you must also make it refer to something at the same time. To declare on you simply make a variable of the type you are going to be referring to, make up your own name, and put an ampersand (&) in front of it:

int &ref;

That creates a reference variable called ref of type integer. Of course this doesn't do anything because you can't assign references to other variables at any other time than declaration. So to make ref refer to something we have to do it in the declaration:

int &ref = x;

This is all assuming we have a variable called x and that it is also an integer (int). But after doing this, anything we do to ref will effect x.
Reference variables :
must be declared as referring to something
must be the same type as the variable they are referring to (in this case it was int).
anything you do to a reference variable affects what it is referring to
When declaring a reference variable you must also make it refer to something at the same time. To declare on you simply make a variable of the type you are going to be referring to, make up your own name, and put an ampersand (&) in front of it:

int &ref;

That creates a reference variable called ref of type integer. Of course this doesn't do anything because you can't assign references to other variables at any other time than declaration. So to make ref refer to something we have to do it in the declaration:

int &ref = x;

This is all assuming we have a variable called x and that it is also an integer (int). But after doing this, anything we do to ref will effect x.
fi will be opened for input, fo will be opened for output
In this case the constructor for both classes will actually open the file if you pass the name as an argument. As well, both classes have an open command (a_file.open()) and a close command (a_file.close()). It is generally a good idea to clean up after yourself and close files once you are finished.
In this case the constructor for both classes will actually open the file if you pass the name as an argument. As well, both classes have an open command (a_file.open()) and a close command (a_file.close()). It is generally a good idea to clean up after yourself and close files once you are finished.